"""
    Author:
    Date: 2019-07-26

    私信管理类
"""

from utils import db
from utils import util


def get_message_count_group_by_day(count):
    """ 获取每天的私信统计数据 """
    sql = f'''
        SELECT      date_format(create_time, '%Y-%m-%d') AS msg_date,
                    count(*) msg_count
        FROM        cmf_users_message
        GROUP BY    msg_date
        ORDER BY    msg_date DESC
        LIMIT       {count};
    '''
    data = db.query_data_from_db(sql)
    return data if data else []


def get_messages_between(begin_time, end_time):
    """ 获取在指定时间段内的私信列表 """
    sql = '''
        SELECT      *,
                    m.id AS mid,
                    u.avatar AS from_avatar,
                    u2.avatar AS to_avatar
        FROM        cmf_users_message AS m
        JOIN        cmf_users AS u ON u.id=m.uid
        JOIN        cmf_users AS u2 ON u2.id=m.touid
        WHERE       m.create_time>=%(begin_time)s AND
                    m.create_time<=%(end_time)s AND
                    m.review=0
        ORDER BY    m.id DESC;
    '''
    params = {
        'begin_time': begin_time,
        'end_time': end_time,
    }
    data = db.query_data_from_db(sql, params)
    pos = len(data)
    for msg in data:
        msg['pos'] = pos
        pos -= 1
    return data if data else []


def set_log_review_status(mid, review):
    """ 设置聊天记录的审核状态 """
    sql = f'''
        UPDATE      cmf_users_message
        SET         review={review}
        WHERE       id={mid}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


if __name__ == '__main__':
    print('ok')

